#!/usr/bin/env python
#coding:utf-8

import MySQLdb
import os,sys
import time,calendar
import glob
import urllib2

PATH = '/var/www/avfun'

DB_USER = 'root'
DB_PASSWD = 'avfun'
DB_NAME = 'avfun'

PERPAGE = 20
PERPAGE2 = 12
PERTOP = 40
PERFB = 40
PERRECENTS = 22
PERTOPART = 7
PERUPDATES = 80

#user rank total display
USERRANK_TOTAL = 400
USERRANK_PERPAGE = 50

#user priviledge
UP_SUPER = 16384
UP_DELETE = 4096
UP_APPROVE = 2048
UP_SUBADMIN = 1024
UP_HIDVIEW = 128
UP_USER = 1

#bbs settings
BBS_LISTSIZE = 20
BBS_THREADSIZE = 20

#user settings
USER_FEEDS = 20
USER_COMMENTS = 10
USER_VISITORS = 6
USER_FRIENDS = 6

#ban arguments
SPAM_COUNT_IN_5MIN = 50

AC_IP = '220.170.79.109'
AC_CAT = {'动画':'http://%s/html/anime/list_1_1.html' % AC_IP,
          '音乐':'http://%s/html/music/list_8_1.html' % AC_IP,
          '游戏':'http://%s/html/game/list_9_1.html' % AC_IP,
          '娱乐':'http://%s/html/ent/list_10_1.html' % AC_IP,
          '番影':'http://%s/html/zj/list_7_1.html' % AC_IP,
          '文章':'http://%s/html/art/list_13_1.html' % AC_IP,}

CAT = {'动画':'/list/anime/1',
       '音乐':'/list/music/1',
       '游戏':'/list/game/1',
       '娱乐':'/list/ent/1',
       '番影':'/list/zj/1',
       '文章':'/list/art/1',}

ECAT = {
	'anime':'动画',
	'music':'音乐',
	'game':'游戏',
	'ent':'娱乐',
	'zj':'番影',
	'art':'文章'
}

ZCAT = {
	'动画':'anime',
	'音乐':'music',
	'游戏':'game',
	'娱乐':'ent',
	'番影':'zj',
	'文章':'art'
}

CATNUM = {'动画':1,
          '音乐':8,
          '游戏':9,
          '娱乐':10,
          '番影':7,
          '文章':13,}

PRELIST = {'动画':'list_1_',
           '音乐':'list_8_',
           '游戏':'list_9_',
           '娱乐':'list_10_',
           '番影':'list_7_',
           '文章':'list_13_',}

def catz2e(cat):
	try:
		cat = cat.encode('utf-8')
	except:
		pass
	if ZCAT.has_key(cat):
		return ZCAT[cat]
	else:
		return 'other'

def getdb():
	return MySQLdb.connect(user=DB_USER,passwd=DB_PASSWD,db=DB_NAME)

def ensure_dir(f):
    d = os.path.dirname(f)
    if not os.path.exists(d):
        os.makedirs(d,0777)

def lastweek_epoch():
	return int(calendar.timegm(time.gmtime())-86400*7+3600*8)

def last_epoch(days=7):
	return int(calendar.timegm(time.gmtime())-86400*days+3600*8)

def timestr2int(timestr,format='%Y-%m-%d %H:%M:%S'):
#	if format == '%Y-%m-%d %H:%M:%S' and timestr[6] == '-':
#		timestr = timestr[:5] + '0' + timestr[5:]
	try:
		x = int(calendar.timegm( time.strptime(timestr,format) ))
	except:
		x = 0 
	return x 

def int2timestr(d,format='%Y-%m-%d %H:%M:%S'):
	return time.strftime( format, time.gmtime(d) ) 

def str2ip(ip):
	if ',' in ip:
		ip = ip[:ip.find(',')]
	ip = ip.split('.')
	ipv4 = 0
	for x in ip[:4]:
		ipv4 = ipv4*256 + int(x)
	return ipv4

def ip2str(ip):
	return '%s.%s.%s.%s' % (ip>>24,(ip>>16)&0xff,(ip>>8)&0xff,ip&0xff)

def clear_cache(dir='list',id=None):
	if id:
		id = str(id)
		fname = PATH + '/data/id/%s/%s/%s.*'%(id[0],id[1:3],id)
		filelist = glob.glob(fname)
		for file in filelist:
			try:
				os.remove(file)
			except Exception as what:
				print what
		return
	if dir == 'all':
		dirs = ['list','rank']
	else:
		dirs = [dir]
	for dir in dirs:
		removeall( PATH+'/data/'+dir )
	try:
		os.remove( PATH+'/data/index.html' )
	except:
		pass

ERROR_STR= """Error removing %(path)s, %(error)s """

def rmgeneric(path, __func__):

    try:
        __func__(path)
        print 'Removed ', path
    except OSError, (errno, strerror):
        print ERROR_STR % {'path' : path, 'error': strerror }
            
def removeall(path):

    if not os.path.isdir(path):
        return
    
    files=os.listdir(path)

    for x in files:
        fullpath=os.path.join(path, x)
        if os.path.isfile(fullpath):
            f=os.remove
            rmgeneric(fullpath, f)
        elif os.path.isdir(fullpath):
            removeall(fullpath)
            f=os.rmdir
            rmgeneric(fullpath, f)

def gmt8str():
	return time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime(time.time()+3600*8))

